﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class lib_ImageUpload : System.Web.UI.Page
{
	protected string FileName { get; set; }
    protected void Page_Load(object sender, EventArgs e)
    {
		Save();
    }
    
    private void Save()
    {
		int pos = Request.ServerVariables["URL"].LastIndexOf("/");
		string _imagehost = string.Format("{0}{1}/FileUpload", Request.ServerVariables["HTTP_ORIGIN"], Request.ServerVariables["URL"].Substring(0, pos));
		
		for(int i=0; i<Request.ServerVariables.Count; i++)
			System.Diagnostics.Debug.WriteLine(Request.ServerVariables[i]);
		
		string UPLOADPATH = Server.MapPath("FileUpload");
		bool isSuccess = false;
		string imgPath = "";
		
		if(Request.Files.Count < 1)
		{
			Message(isSuccess, imgPath, "Error");
			return;
		}
		
		HttpPostedFile file = Request.Files[0];
		FileName = GetName(file.FileName);
		if(string.IsNullOrEmpty(FileName))
		{
			Message(isSuccess, imgPath, "Error");
			return;
		}
		
		file.SaveAs(System.IO.Path.Combine(UPLOADPATH, FileName));
		isSuccess = true;
		imgPath = string.Format("{0}/{1}", _imagehost, FileName);
		Message(isSuccess, imgPath, "");
    }
    
    public void Message(bool isSuccess, string fileUrl, string errorMessage)
    {
		string result = string.Format(" success:{0}, file_url:'{1}', message:'{2}' ", isSuccess.ToString().ToLower(), fileUrl, errorMessage);
		this.body1.InnerHtml = "{" + result + "}";
    }
    
    public string GetName(string fileName)
    {
		int lastCount = fileName.LastIndexOf(".");
		string fileType = fileName.Substring(lastCount, (fileName.Length - lastCount)).ToLower();
		string saveFileName = string.Empty;
		
		if(fileType == ".jpg" || fileType == ".jpeg" || fileType == ".gif" || fileType == ".png")
			saveFileName = DateTime.Now.Ticks.ToString() + fileType;
			
		return saveFileName;
    }
}
